// noinspection JSUnusedGlobalSymbols
/**
 * 简单的 {@link Storage} 包装, 处理序列化 重用 key
 * @author 冰凝
 * @date 2022-10-24 01:32:40
 */
export class StorageItem<T = any> {
    private readonly storage: Storage
    private readonly key: string

    constructor(storage: Storage, key: string) {
        this.storage = storage
        this.key = key
    }

    public get(): T | null {
        const str = this.storage.getItem(this.key)
        if (!str) {
            return null
        }
        return JSON.parse(str)
    }

    /**
     * 如果存在?
     */
    public ifPresent(consumer: (value: T) => void) {
        const value = this.get()
        if (value) {
            consumer(value)
        }
    }

    public set(value: T): void {
        this.storage.setItem(this.key, JSON.stringify(value))
    }

    public remove() {
        this.storage.removeItem(this.key)
    }

}
